<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // 降低全局变量带来的命名污染
      // 1.使用命名空间
      // 对象字面量
      var namespace1 = {
        a: function () {
          console.log(1)
        },
        b: function () {
          console.log(2)
        },
      }

      // 动态创建命名空间
      var MyApp = {}

      MyApp.namespace = function (name) {
        var parts = name.split('.')
        var current = MyApp
        for (var i in parts) {
          if (!current[parts[i]]) {
            current[parts[i]] = {}
          }
          current = current[parts[i]]
        }
      }

      MyApp.namespace('event')
      MyApp.namespace('dom.style')

      console.dir(MyApp)
      // 等同于
      var MyApp = {
        event: {},
        dom: {
          style: {},
        },
      }

      // 2.使用闭包封装私有变量
      var user = (function () {
        var _name = 'wangxin',
          age = 22

        return {
          getUSerInfo: function () {
            return _name + '-' + _age
          },
        }
      })()
    </script>
  </body>
</html>
